﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ww.wwf.wwfbll;
using System.IO;
using System.Collections;
namespace ww.form.wwf
{
    public partial class UserdefinedTypeDemoForm : SysBaseForm
    {
        UserdefinedBLL bll = new UserdefinedBLL();
        ww.wwf.wwfbll.ExcelHelper excelhelp = new ExcelHelper("","");
        string strftemplate = "";//模板ID
        string strTabelid = "";//表ID
        DataTable dtTable = new DataTable();//当前表
        DataTable dtColumns = new DataTable();//当前表列

        DataTable dtCurrTable = new DataTable();

        string dbCreatTemTableName = ""; //当前要建临时表

        public  DataTable dtYSValue = new DataTable();//设置原始值
        public UserdefinedTypeDemoForm()
        {
            InitializeComponent();
        }

        private void UserdefinedTypeDemoForm_Load(object sender, EventArgs e)
        {
            GetTree("0");
        }
        private void button1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wwTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                this.dtTable=new DataTable();                    
                this.dtColumns=new DataTable();                   
                this.dtYSValue=new DataTable();
                    
                strTabelid = e.Node.Name.ToString();
                dtTable = this.bll.BllTypeDTByftable_id(strTabelid);
                if (dtTable.Rows.Count > 0)
                {
                    string ftype = dtTable.Rows[0]["ftype"].ToString();//表类型 只表才做运行
                    this.strftemplate = dtTable.Rows[0]["ftemplate"].ToString();//导出模板
                    int fsum_flag = Convert.ToInt32(dtTable.Rows[0]["fsum_flag"].ToString());//有合计否
                    if (ftype == "表")
                    {
                        this.dtColumns = this.bll.BllColumnsByftable_id(strTabelid);
                        if (this.dtColumns.Rows.Count > 0)
                        {
                            #region 创建数据临时表 并取出公式值
                            this.dbCreatTemTableName = "tem_" + this.bll.DbGuid();
                            //string sqlCreate = "create table " + dbCreatTemTableName + "(pk_accsubj char(20),subjcode varchar(30),subjname varchar(40),dispname varchar(200),unit varchar(10))";
                            //string sqlCreate = "create table " + dbCreatTemTableName + " (fid,";//要创建的列
                            StringBuilder sqlCreate = new StringBuilder();//创建sql
                            StringBuilder sqlInsertCol = new StringBuilder();//插入的列
                           
                            StringBuilder sqlGetGS = new StringBuilder();//取得公式
                            sqlInsertCol.Append("INSERT INTO " + dbCreatTemTableName + "  (fid");
                            DataColumn columnFid = new DataColumn("fid", typeof(string));
                            this.dtYSValue.Columns.Add(columnFid);

                            sqlCreate.Append("create table " + dbCreatTemTableName + " (fid varchar(32)");
                            string strColumnName = "";//列名
                            string strfvalue_type = "";//值类型
                            string strfvalue_content = "";//公式值

                            //MessageBox.Show("dd");
                            for (int i = 0; i < dtColumns.Rows.Count; i++)
                            {
                                strfvalue_type = dtColumns.Rows[i]["fvalue_type"].ToString();
                                strfvalue_content = dtColumns.Rows[i]["fvalue_content"].ToString();
                                strColumnName = dtColumns.Rows[i]["fcode"].ToString();
                                if (strfvalue_type == "公式值")
                                {
                                    sqlGetGS.Append(",(" + strfvalue_content + ") as " + strColumnName);
                                }
                                else
                                {
                                    sqlCreate.Append("," + strColumnName + " varchar(50)");
                                    sqlInsertCol.Append("," + strColumnName);

                                    DataColumn column = new DataColumn(strColumnName, typeof(string));
                                    this.dtYSValue.Columns.Add(column);
                                }
                            }

                            sqlCreate.Append(")");
                            string sql = "SELECT * " + sqlGetGS.ToString() + " FROM " + this.dbCreatTemTableName + " order by fid";
                           
                            this.bll.BllTemTableCreate(sqlCreate.ToString());//临时表创建
                            #endregion

                            #region 给临时表设置原始值
                            BllSetdtYSValue();
                            
                            IList sqlList = new ArrayList();
                            for (int intYS = 0; intYS < dtYSValue.Rows.Count; intYS++)
                            {
                                StringBuilder sqlInsertColValue = new StringBuilder();//插入的列 值
                                for (int intYSC = 0; intYSC < dtYSValue.Columns.Count; intYSC++)
                                {
                                    if (intYSC == 0)
                                        sqlInsertColValue.Append("'" + dtYSValue.Rows[intYS][intYSC].ToString() + "'");
                                    else
                                        sqlInsertColValue.Append(",'" + dtYSValue.Rows[intYS][intYSC].ToString() + "'");

                                }                               
                                string sqlInsert = sqlInsertCol.ToString() + ") VALUES ("+ sqlInsertColValue.ToString() + ")";
                                sqlList.Add(sqlInsert);
                             
                             
                            }
                            MessageBox.Show(this.bll.BllTemTableInsertBusiness(sqlList));
                            #endregion

                            #region 取出临时表的值
                            this.textBox1.Text = sql;
                            DataTable dtDBTemTable = this.bll.BllTemTableDT(sql); //
                            #endregion


                            #region 求和
                            if (fsum_flag == 1)
                            {
                                //计算合计                               
                                string strCurrColumn = "";//当前列名
                                string strfsum_flag = "0";//求和否
                                string strfxsws = "0";//小数位数
                                DataRow drRowSum = dtDBTemTable.NewRow();
                                drRowSum[0] = "合  计";
                                for (int c = 0; c < dtDBTemTable.Columns.Count; c++)
                                {
                                    strCurrColumn = dtDBTemTable.Columns[c].ColumnName.ToString();

                                    //fcode
                                    DataRow[] currcolumXS = dtColumns.Select("fcode='" + strCurrColumn + "'");
                                    if (currcolumXS != null)
                                    {
                                        foreach (DataRow drXS in currcolumXS)
                                        {
                                            strfsum_flag = drXS["fsum_flag"].ToString();
                                            strfxsws = drXS["fxsws"].ToString();
                                        }
                                    }
                                    if (strfsum_flag == "1")
                                    {
                                        if (strfxsws == "" || strfxsws == null)
                                            strfxsws = "2";
                                        Decimal decSumValue = 0;
                                        for (int isum = 0; isum < dtDBTemTable.Rows.Count; isum++)
                                        {                                            
                                            if (dtDBTemTable.Rows[isum][strCurrColumn].ToString() == "" || dtDBTemTable.Rows[isum][strCurrColumn].ToString() == null)
                                            {
                                                decSumValue = decSumValue + 0;
                                            }
                                            else
                                            {
                                                dtDBTemTable.Rows[isum][strCurrColumn]=BllGetXSWS(Convert.ToDecimal(dtDBTemTable.Rows[isum][strCurrColumn].ToString()), Convert.ToInt32(strfxsws));
                                                decSumValue = decSumValue + Convert.ToDecimal(dtDBTemTable.Rows[isum][strCurrColumn].ToString());
                                            }
                                        }
                                        //MessageBox.Show(decSumValue.ToString());
                                        decSumValue = BllGetXSWS(decSumValue, Convert.ToInt32(strfxsws));
                                       // if (decSumValue != 0)
                                        drRowSum[strCurrColumn] = decSumValue;
                                    }
                                }
                                dtDBTemTable.Rows.Add(drRowSum);
                            }
                            #endregion
                            this.dataGridView1.DataSource = dtDBTemTable;
                            this.bll.BllTemTableDel(this.dbCreatTemTableName);//临时表删除
                        }                        
                    }
                }
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
            finally
            {
                // this.bll.BllTemTableDel(this.dbCreatTemTableName);//临时表删除
            }
        }


        public void BllSetdtYSValue()
        {
            string strFid = "";
            for (int iv = 0; iv < 4; iv++)
            {
                DataRow drTT = dtYSValue.NewRow();
                if (iv.ToString().Length == 1)
                    strFid = "000" + iv.ToString();
                if (iv.ToString().Length == 2)
                    strFid = "00" + iv.ToString();
                if (iv.ToString().Length == 3)
                    strFid = "0" + iv.ToString();
                //drTT = dtYSValue.NewRow();
                for (int i = 0; i < this.dtYSValue.Columns.Count; i++)
                {
                    string str = this.dtYSValue.Columns[i].ColumnName.ToString();
                    if (str == "fid")
                        drTT[str] = strFid.ToString();
                    else
                        drTT[str] = iv+i+5.4368;
                }
                this.dtYSValue.Rows.Add(drTT);
            }
            dataGridView2.DataSource = this.dtYSValue;

        }


        /// <summary>
        /// 列出系统部门树
        /// </summary>
        public void GetTree(string pid)
        {
            try
            {
                this.wwTreeView1.ZADataTable = this.bll.BllTypeDT(2);
                this.wwTreeView1.ZATreeViewRootValue = pid;//树 RootId　根节点值
                this.wwTreeView1.ZAParentFieldName = "fp_id";//上级字段名称
                this.wwTreeView1.ZADisplayFieldName = "fname";//显示字段名称
                this.wwTreeView1.ZAKeyFieldName = "ftable_id";//主键字段名称
                this.wwTreeView1.ZATreeViewShow();//显示树        
                try
                {
                    this.wwTreeView1.SelectedNode = wwTreeView1.Nodes[0];
                }
                catch { }

            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }
        
       
        /// <summary>
        /// 据数据列创建临时表
        /// </summary>
        private DataTable CreateCurrTable(string ftable_id)
        {
           
            //int intxsws = 2;            
            dtColumns = new DataTable();
            dtCurrTable = new DataTable();
            //数据表创建 1

            if (dtColumns.Rows.Count > 0)
            {
                string strColumnName = "";//列表
                for (int i = 0; i < dtColumns.Rows.Count; i++)
                {
                    strColumnName = dtColumns.Rows[i]["fcode"].ToString();
                    DataColumn column = new DataColumn(strColumnName, typeof(string));
                    dtCurrTable.Columns.Add(column);
                }

            }
            return dtCurrTable;
        }

        /// <summary>
        /// 取得小数位数
        /// </summary>
        /// <returns></returns>
        public Decimal BllGetXSWS(Decimal decValue, int intWX)
        {
            Decimal decr = 0;
            switch (intWX)
            {
                case 1:
                    decr = Decimal.Parse(decValue.ToString("0.0"));
                    break;
                case 2:
                    decr = Decimal.Parse(decValue.ToString("0.00"));
                    break;
                case 3:
                    decr = Decimal.Parse(decValue.ToString("0.000"));
                    break;
                case 4:
                    decr = Decimal.Parse(decValue.ToString("0.0000"));
                    break;
                case 5:
                    decr = Decimal.Parse(decValue.ToString("0.00000"));
                    break;
                case 6:
                    decr = Decimal.Parse(decValue.ToString("0.000000"));
                    break;
                default:
                    decr = Decimal.Parse(decValue.ToString("0.00"));
                    break;
            }
            return decr;
        }



        /// <summary>
        /// 当前GridView设置
        /// </summary>
        private void CurrGridViewSet(DataTable dtColumns)
        {
            try
            {
                for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
                {
                    string strCurrColName = this.dataGridView1.Columns[i].Name.ToString();
                    DataRow[] colList = dtColumns.Select("fcode='" + strCurrColName + "'");
                    int fshow_width = 100;//宽度
                    int fshow_flag = 1;//显示标识               
                    string fname = "";//列名
                    this.dataGridView1.Columns[strCurrColName].Visible = false;
                    if (colList.Length > 0)
                    {
                        foreach (DataRow drC in colList)
                        {
                            if (drC["fshow_width"].ToString() == "" || drC["fshow_width"].ToString() == null)
                            {
                            }
                            else
                            {
                                fshow_width = Convert.ToInt32(drC["fshow_width"].ToString());
                            }
                            if (drC["fshow_flag"].ToString() == "" || drC["fshow_flag"].ToString() == null)
                            {
                            }
                            else
                            {
                                fshow_flag = Convert.ToInt32(drC["fshow_flag"].ToString());
                            }
                            fname = drC["fname"].ToString();
                        }
                        if (fshow_flag == 1)
                        {
                            this.dataGridView1.Columns[strCurrColName].Visible = true;
                            this.dataGridView1.Columns[strCurrColName].Width = fshow_width;
                            this.dataGridView1.Columns[strCurrColName].HeaderText = fname;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }

        private void BllExcelOut()
        {
            try
            {
                this.Validate();
                this.dataGridView1.EndEdit();                
                this.excelhelp.GridViewToExcel(this.dataGridView1, this.strftemplate, 3, 1);

            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }

        private void butExcel_Click(object sender, EventArgs e)
        {
            BllExcelOut();
        }

        private void 报告列表设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                UserdefinedFieldUpdateForm userf = new UserdefinedFieldUpdateForm(strTabelid);
                userf.ShowDialog();
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            BllExcelOut();
        }

       

    }
}